<?php
class uuser extends Model {
	/**
	 * 验证用户名密码
	 *
	 * @param unknown_type $username        	
	 * @param unknown_type $password        	
	 * @return array( 'result', 'userinfo', 'msg') | boolean
	 *         result:成功：id 密码错误：-1 用户不存在：-2
	 *         userinfo：用户信息
	 *         msg：描述
	 */
	public function authUser($user, $password) {
		$result = array ();
		$userinfo = $this->getUserFromPhone ( $user );
		
		if ($userinfo) {
			if ($userinfo ['user_pw'] == $this->generatePw ( $password, $userinfo ['user_salt'] )) {
				$result ['result'] = $userinfo ['user_id'];
				$result ['userinfo'] = $userinfo;
				$result ['msg'] = "验证错误";
			} else {
				$result ['result'] = - 1;
				$result ['userinfo'] = null;
				$result ['msg'] = "密码错误";
			}
		} else {
			$result ['result'] = - 2;
			$result ['userinfo'] = null;
			$result ['msg'] = "用户不存在";
		}
		return $result;
	}
	/**
	 * 根据用户id获取用户信息
	 *
	 * @param int $userid        	
	 * @return Ambigous <boolean, multitype:>
	 */
	public function getAdminFromAdminid($userid) {
		$sql = "select `uuser`.*,`role`.* from `uuser`
				LEFT JOIN `role` ON `uuser`.`role_id` = `role`.`role_id`
				where `uuser`.`user_id` = '" . $userid . "' ";
		// echo $sql;
		return $this->fetchRow ( $sql );
	}
	/**
	 * 根据用户手机号获取用户信息
	 * return false / array()
	 */
	public function getUserFromPhone($val) {
		$sql = "select `uuser`.*,`role`.* from `uuser`
				LEFT JOIN `role` ON `uuser`.`role_id` = `role`.`role_id`
				where `uuser`.`user_phone` = '" . $val . "' ";
		// echo $sql;
		return $this->fetchRow ( $sql );
	}
	/**
	 * 添加用户
	 * return: 用户存在：-1 插入失败：0 注册成功：用户id
	 */
	public function addUser($phoneNum, $pw, $subjectID, $nickName, $roleid, $isStudent) {
		$result = $this->userCanUse ( $phoneNum ); // 检查是否有非法字符,或者是否存在
		                                           // echo $result;
		if ($result > 0) {
			// 插入数据
			$salt = $this->_getSalt ();
			$pw = $this->generatePw ( $pw, $salt );
			$sql = "INSERT INTO `uuser`
						( `user_pw`, `user_salt`, `role_id`, `user_create_time`, `user_phone`, `sub_id`, `user_nickname`)
						VALUES
						( '" . $pw . "', '" . $salt . "', '" . $roleid . "', NOW(), '" . $phoneNum . "','" . $subjectID . "','" . $nickName . "')";
			// echo $sql;
			return $this->insert ( $sql );
		} else {
			return $result;
		}
	}
	/**
	 * 添加用户的手机设备信息
	 *
	 * @param unknown_type $userid        	
	 * @param unknown_type $osType        	
	 * @param unknown_type $token        	
	 * @return boolean resource
	 */
	public function setPhoneInfo($userid, $osType, $token) {
		if (strtolower ( $osType ) == "android") {
			$osid = 1;
		} else if (strtolower ( $osType ) == "ios") {
			$osid = 2;
		} else {
			return false;
		}
		$sql = "SELECT * FROM `uuser` WHERE `code_platform` =" . $osid . " AND `user_token` = '" . $token . "' ";
		if ($result = $this->fetchRow ( $sql )) {
			
			if ($result ["user_id"] != $userid) {
				
				$this->delPhoneInfo ( $result ["user_id"] );
				
				$sql = "UPDATE `uuser` SET `code_platform` = '" . $osid . "',`user_token` = '" . $token . "' WHERE `uuser`.`user_id` =" . $userid . " ";
				return $this->update ( $sql );
			}
		} else {
			$sql = "UPDATE `uuser` SET `code_platform` = '" . $osid . "',`user_token` = '" . $token . "' WHERE `uuser`.`user_id` =" . $userid . " ";
			return $this->update ( $sql );
		}
	}
	/**
	 * 删除账号登录的手机信息
	 *
	 * @param unknown_type $userid        	
	 * @return resource
	 */
	public function delPhoneInfo($userid) {
		$sql = "UPDATE `uuser` SET `code_platform` = '0',`token` = NULL WHERE `uuser`.`user_id` =" . $userid . " ";
		return $this->update ( $sql );
	}
	
	/**
	 *
	 * @param unknown_type $uid        	
	 * @param unknown_type $pw        	
	 * @return string boolean
	 */
	public function setPw($uid, $pw) {
		$salt = $this->_getSalt ( $uid );
		$password = $this->generatePw ( $pw, $salt );
		if ($this->modUserInfo ( $uid, array (
				'user_pw' => $password,
				'user_salt' => $salt 
		) )) {
			return true;
		} else {
			return false;
		}
	}
	
	/**
	 * 修改用户资料
	 *
	 * @param $userId用户id ,$arr[key]
	 *        	= value
	 * @return bool
	 */
	public function modUserInfo($userId, $arr) {
		if ($arr) {
			reset ( $arr );
			// list ( $key, $val ) = each ( $arr );
			// $str = " `" . $key . "` = '" . $val . "' ";
			while ( list ( $key, $val ) = each ( $arr ) ) {
				if ($val !== "") { // 比较类型和数据
					$str .= " , `" . $key . "` = '" . $val . "' ";
				} else {
					$str .= " , `" . $key . "` = null ";
				}
			}
			$str = substr ( $str, 2, strlen ( $str ) );
			$sql = "UPDATE `uuser` SET " . $str . " WHERE `user_id` =" . $userId . "  LIMIT 1";
			// $fp = fopen ( "modinfo.txt", "w+" );
			// fwrite ( $fp, $sql );
			// fclose ( $fp );
			// echo $sql;
			return $this->update ( $sql );
		} else {
			return false;
		}
	}
	
	/**
	 * 生成加密后的密码
	 *
	 * @param unknown_type $pw        	
	 * @param unknown_type $salt        	
	 * @return string
	 */
	public function generatePw($pw, $salt) {
		return md5 ( md5 ( $pw . $salt ) );
	}
	/**
	 * 查看用户名是否可用
	 *
	 * @param unknown_type $username        	
	 * @return -2 非法字符 -3已注册为学生 -4已注册为教师 -1其他情况 1可用
	 */
	public function userCanUse($username) {
		if ($this->haveBadTag ( $username )) {
			return - 2;
		}
		$data = $this->getUserFromPhone ( $username );
		if (!$data) {
			return 1;
		} else if ($data['role_id'] == '6') {
			return -3;
		} else if ($data['role_id'] == '2' || $data['role_id'] == '3' || $data['role_id'] == '4' || $data['role_id'] == '5' ) {
			return -4;
		} else {
			return -1;
		}
	}
	
	/**
	 * 获取一个随机生成的字符串
	 *
	 * @param unknown_type $username        	
	 */
	protected function _getSalt($str = "") {
		return substr ( md5 ( $str . time () ), 2, 16 );
	}
	
	/**
	 * 根据用户id获取用户信息
	 *
	 * @author linkai
	 *        
	 * @param int $userid        	
	 * @return Ambigous <boolean, multitype:>
	 */
	public function GetPersonDetailByUserID($userID) {
		$sql = "SELECT `u`.*,`s`.`sub_cont`,`p`.`pic_link`,`a`.*,
					`ap`.`pid` as `ppid` , `ap`.`name` as `pname` ,`app`.`name` as `ppname` 
				FROM `uuser` AS `u`
				LEFT JOIN `subject` AS `s` ON `s`.`sub_id`=`u`.`sub_id` 
				LEFT JOIN `picture` AS `p` ON `p`.`pic_id`=`u`.`user_icon_id`
				LEFT JOIN `yitao_province` AS `a` ON `a`.`id`=`u`.`user_place` 
				LEFT JOIN `yitao_province` AS `ap` ON `ap`.`id`=`a`.`pid` 
				LEFT JOIN `yitao_province` AS `app` ON `app`.`id`=`ap`.`pid` 
				WHERE `user_id`=" . $userID;
		// 根据user_place 搜索省市区
		return $this->fetchRow ( $sql );
	}
	
	/**
	 * 修改资料
	 *
	 * @author linkai
	 *        
	 * @return bool
	 */
	public function SavePersonDetail($userID, $realName, $nickName, $gender, $birthday, $areaID, $subjectID, $school, $class, $acountQQ, $accountMail, $accountWeixin, $accountRenren) {
		$sql = "UPDATE `uuser`
				SET `user_nickname`='" . $nickName . "' ,
					`user_realname`='" . $realName . "' ,
					`user_gender`='" . $gender . "',
					`user_birth`='" . $birthday . "',
					`user_place`=" . $areaID . ",
					`user_school`='" . $school . "',
					`user_class`='" . $class . "',
					`sub_id`='" . $subjectID . "',
					`user_qq`='" . $acountQQ . "',
					`user_mail`='" . $accountMail . "',
					`user_weixin`='" . $accountWeixin . "',
					`user_renren`='" . $accountRenren . "' 
				WHERE `user_id` =" . $userID;
		return $this->update ( $sql );
	}
	
	/**
	 * 修改科目
	 *
	 * @author linkai
	 *        
	 * @param int $userID        	
	 * @param int $subID        	
	 * @param int $reason        	
	 * @return bool
	 */
	public function ModifyPersonSubject($userID, $subID, $reason) {
		$sql = "UPDATE `uuser`
				SET `sub_id` = " . $subID . " ,
					`user_change_sub_reason` = '" . $reason . "' 
				WHERE `user_id` = " . $userID;
		return $this->update ( $sql );
	}
	
	/**
	 * 更新头像
	 *
	 * @author linkai
	 *        
	 * @param int $userID        	
	 * @param int $fileID        	
	 * @return bool
	 */
	public function UpdateIcon($userID, $fileID) {
		$sql = "UPDATE `uuser`
				SET `user_icon_id` = " . $fileID . " 
				WHERE `user_id` = " . $userID;
		return $this->update ( $sql );
	}
	
	/**
	 * 获取教师信息
	 *
	 * @param unknown_type $id        	
	 * @return Ambigous <boolean, multitype:>
	 */
	public function getteacherlist($id = NULL, $page = 1, $num = 8, $key = NULL) {
		if (! $id) {
			$sql = "SELECT `uuser`.*, `subject`.`sub_cont` FROM `uuser`
					LEFT JOIN `subject` ON `subject`.`sub_id` = `uuser`.`sub_id`
					LEFT JOIN `role` ON `role`.`role_id` = `uuser`.`role_id`
					";

			if($key){
				$where = " WHERE `uuser`.`user_nickname` LIKE '%".$key."%' ";
			}else{
				$where = " WHERE 1";
			}
			$filter = " AND (`uuser`.`role_id` = 2 OR `uuser`.`role_id` = 3 OR `uuser`.`role_id` = 4  OR `uuser`.`role_id` = 5)";
			$limit = " ORDER BY `user_create_time` DESC LIMIT " . ($page - 1) * $num . ", " . $num . "";

			$limit = " LIMIT " . ($page - 1) * $num . ", " . $num . "";

			$list = $this->fetchAll ( $sql . $where . $filter .$limit );
			$total = count ( $this->fetchAll ( $sql .$where . $filter) );
			$totalPage = ceil ( $total / $num );
			//echo $total;
			return array (
				'page' => $page,
				'list' => $list,
				'total' => $total,
				'totalPage' => $totalPage 
			);
		} else {
			$sql = "SELECT `uuser`.*, `subject`.`sub_cont`, SUM(`score`.`score_score`) AS totalscore FROM `uuser`
					LEFT JOIN `subject` ON `subject`.`sub_id` = `uuser`.`sub_id`
					LEFT JOIN `score` ON `score`.`user_id` = `uuser`.`user_id`
					WHERE `uuser`.`user_id` = '" . $id . "'";
			// echo $sql;
			return $this->fetchRow ( $sql );
		}
	}
	
	/**
	 * 更新教师信息
	 *
	 * @param unknown_type $userid        	
	 * @param unknown_type $username        	
	 * @param unknown_type $usertel        	
	 * @param unknown_type $userrole        	
	 * @return resource
	 */
	public function updateteacher($userid, $username, $usertel, $userrole = NULL) {
		$sql = "UPDATE `uuser` SET 
				`user_nickname` = '" . $username . "',
				`user_phone` = '" . $usertel . "',
				`role_id` = '" . $userrole . "'
				WHERE `user_id` = " . $userid;
		// echo $sql;
		return $this->update ( $sql );
	}
	
	/**
	 * 删除教师
	 *
	 * @param unknown_type $userid        	
	 * @return resource
	 */
	public function delteacher($userid) {
		$sql = "DELETE FROM `uuser`
				WHERE `uuser`.`user_id` = " . $userid;
		return $this->del ( $sql );
	}
	
	/**
	 * 获取学生
	 *
	 * @return Ambigous <boolean, multitype:>
	 */
	public function getstudentlist($page = 1, $num = 8 ,$key = NULL) {
		$sql = "SELECT `uuser`.*  FROM `uuser`
				";
		if($key){
			$where = " WHERE `uuser`.`user_nickname` LIKE '%".$key."%' AND `uuser`.`role_id` = 6 ";
		}else{
			$where = " WHERE `uuser`.`role_id` = 6";
		}
		$limit = " LIMIT " . ($page - 1) * $num . ", " . $num . "";
		$list = $this->fetchAll ( $sql . $where .$limit );
		$total = count ( $this->fetchAll ( $sql . $where ) );
		$totalPage = ceil ( $total / $num );
		//echo $sql.$where;
		return array (
				'page' => $page,
				'list' => $list,
				'total' => $total,
				'totalPage' => $totalPage
		);
	}
	
	/**
	 * 获取积分
	 * @param unknown_type $id
	 * @return Ambigous <boolean, multitype:>
	 */
	public function gettotalscore($id){
		$sql = "SELECT SUM(`score_score`) AS totalscore FROM `score`
				WHERE `user_id` = " . $id .
				" GROUP BY `user_id`" ;
		//echo $sql;
		return $this->fetchRow($sql);
	}
	
	/**
	 * 获取token
	 * @param unknown_type $roleId
	 * @return Ambigous <boolean, multitype:>
	 */
	public function getToken($roleId){
		$sql = "SELECT `uuser`.`user_token`,`uuser`.`role_id` FROM `uuser` ";
		if ($roleId != 0){
			if ($roleId == 1){
				$sql .= "WHERE `role_id` != 6 ";
			}else {
				$sql .= "WHERE `role_id` = '".$roleId."' ";
			}
		}
		return $this->fetchAll($sql);
	}
}